package com.qo.qsdk.ui.base;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.ClientCertRequest;
import android.webkit.HttpAuthHandler;
import android.webkit.JsResult;
import android.webkit.RenderProcessGoneDetail;
import android.webkit.SafeBrowsingResponse;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;

import androidx.annotation.RequiresApi;

import com.qo.qsdk.ui.QSDKListener;
import com.qo.qsdk.ui.view.Html5WebView;
import com.qo.qsdk.utils.DynamicUtils;
import com.qo.qsdk.utils.Language;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;

import static android.webkit.WebSettings.LOAD_NO_CACHE;

import com.qo.qsdk.ui.base.third.Px7TextView;
import com.qo.qsdk.ui.base.third.Px9TextView;
import com.qo.qsdk.ui.base.third.Px9EditText;
import com.qo.qsdk.ui.base.third.StrokeTextView;
import com.qo.qsdk.ui.base.third.StrokeTextViewY;
public class AppleAuthView {

    private Px9TextView mClose;
    private Activity mActivity;
    private QSDKListener mQSDKListener;
    private FrameLayout mFlContent;
    private Html5WebView mWebView;

    public AppleAuthView(Activity mActivity, QSDKListener qsdkListener) {
        this.mActivity = mActivity;
        this.mQSDKListener = qsdkListener;
        this.mActivity.setContentView(DynamicUtils.layout(this.mActivity, "qsdk_auth_apple"));
        init(mActivity);
    }

    private void init(Activity v) {
//        mTitle = v.findViewById(DynamicUtils.id(mActivity, "title"));
        mClose = v.findViewById(DynamicUtils.id(mActivity, "close"));
        mFlContent = v.findViewById(DynamicUtils.id(mActivity, "flContent"));
        mClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v2) {
                if (mQSDKListener != null) mQSDKListener.onAppleAuthClose();
                if (!v.isFinishing()) v.finish();
            }
        });
        v.findViewById(DynamicUtils.id(mActivity, "re")).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                show(activity, title, url);
            }
        });

        if (mWebView == null) {
            mWebView = new Html5WebView(v);
            FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
                    FrameLayout.LayoutParams.MATCH_PARENT,
                    FrameLayout.LayoutParams.MATCH_PARENT);
            mFlContent.addView(mWebView, 0, layoutParams);
            mWebView.setBackgroundColor(0);
        }
        mWebView.setWebViewClient(new Html5WebViewClient());
        mWebView.setWebChromeClient(new Html5WebChromeClient());
        mWebView.getSettings().setCacheMode(LOAD_NO_CACHE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
        }
    }

    private String title, url;
    private Activity activity;
    public void show(Activity activity, String title, String url) {
        this.title = title;
        this.activity = activity;
        this.url = url;
        refresh();
//        mTitle.setText(title);
        loadUrl(url);
    }

    private void loadUrl(String url) {
        mWebView.loadUrl(url);
    }

    private void refresh() {
        mClose.setText(Language.Float_Close.toString());
    }

    public class Html5WebViewClient extends WebViewClient {

        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {

            Log.i("TAG", request.getUrl().toString());

            try {
                return exec(request.getUrl().toString());
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
            }


            return true;
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            Log.i("TAG", url);

            try {
                return exec(url);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
            }

            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            if (exec(url)) {
                super.onPageStarted(view, url, favicon);
            }
        }

        @Override
        public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
            try {
                AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
                builder.setMessage(Language.Float_Ssl_Error.toString());
                builder.setPositiveButton(Language.Float_Ssl_Error_Enter.toString(), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        handler.proceed();// 接受https所有网站的证书
                    }
                });

                builder.setNegativeButton(Language.Float_Ssl_Error_Cancel.toString(), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        handler.cancel();
                    }
                });

                AlertDialog dialog = builder.create();
                dialog.show();
            }catch (Exception e){
                if (handler != null) handler.cancel();
            }
        }
    }

    private class Html5WebChromeClient extends WebChromeClient {
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            Log.e("TAG", "title:" + title);
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
        }

        @Override
        public  boolean  onJsAlert(WebView  view,  String  url,  String  message,  final JsResult result)  {

            AlertDialog d = new AlertDialog.Builder(mActivity)
                    .setMessage(message)
                    .setPositiveButton("Ok",  new  DialogInterface.OnClickListener()  {
                        public  void  onClick(DialogInterface  dialog,  int  which)  {
                            result.confirm();
                        }
                    }).create();
            d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
            d.show();
            return  true;
        }

        @Override
        public  boolean  onJsConfirm(WebView  view,  String  url,  String  message,  final  JsResult  result)  {
            AlertDialog d = new  AlertDialog.Builder(mActivity)
                    .setMessage(message)
                    .setPositiveButton("Ok",  new  DialogInterface.OnClickListener()  {
                        public  void  onClick(DialogInterface  dialog,  int  which)  {
                            result.confirm();
                        }
                    })
                    .setNegativeButton("No",  new  DialogInterface.OnClickListener()  {
                        public  void  onClick(DialogInterface  dialog,  int  which) {
                            result.cancel();


                        }
                    }).create();
            d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
            d.show();
            return true;
        }
    }

    private boolean exec(String url) {
        if (url != null && url.startsWith("unicorn://")) {
            String[] a = url.split("unicorn://");
            String r = a[1];
            try {
                JSONObject result = new JSONObject(r);
                int code = result.getInt("code");
                if (code == 0) {
                    if (mQSDKListener != null) {
                        mQSDKListener.onAppleAuthSuccess(result.getString("data"));
                        mQSDKListener = null;
                    }
                }else{
                    if (mQSDKListener != null) {
                        mQSDKListener.onAppleAuthFail();
                        mQSDKListener = null;
                    }
                }
                if (mActivity != null && !mActivity.isFinishing()) mActivity.finish();
                return false;
            } catch (JSONException e) {
                e.printStackTrace();
                if (mQSDKListener != null) {
                    mQSDKListener.onAppleAuthFail();
                    mQSDKListener = null;
                }
                if (mActivity != null && !mActivity.isFinishing()) mActivity.finish();
            }
        }
        return true;
    }
}
